package com.maimao.kill.service;

import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Maps;
import com.maimao.core.exception.MaiMaoDaoException;
import com.maimao.kill.mapper.KillRequirementMapper;
import com.maimao.model.kill.KillRequirement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author MaoLin Wang
 * @date 2021/4/11 10:02 上午
 */
@Service
public class RequirementService {

    public static final Map<Integer, KillRequirement> REQUIREMENT_CACHE = Maps.newHashMapWithExpectedSize(2);

    @Autowired
    private KillRequirementMapper killRequirementMapper;

    /**
     * 单品秒杀编号
     */
    public static final Integer SEC_KILL_ACTIVITY_ID = 2;

    /**
     * 初始化要求
     */
    @PostConstruct
    public void refreshRequirement() {
        List<KillRequirement> killRequirements = killRequirementMapper.selectAll();
        if (ObjectUtil.isNotEmpty(killRequirements)) {
            Map<Integer, KillRequirement> map = killRequirements.stream().collect(Collectors.toMap(KillRequirement::getActivityId, x -> x));
            REQUIREMENT_CACHE.putAll(map);
        }
    }

    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public void add(KillRequirement killRequirement) {
        killRequirementMapper.insert(killRequirement);
    }

    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public void update(KillRequirement killRequirement) {
        killRequirementMapper.updateById(killRequirement);
        refreshRequirement();
    }

    public KillRequirement queryOne(Integer id) {
        return killRequirementMapper.selectByActivityId(id);
    }
}
